import json
import select
import socket
import sys
import time
from common_client import *
PLAYER_NAME='BOT_select_first'

def listen(start=False):
	global ssock
	ssock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
	#ssock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
	ssock.connect((HOST, PORT))
	print('connected:', ssock)
	send_msg(ssock,set_name(PLAYER_NAME))
	time.sleep(1)
	if start:
		send_msg(ssock, start_game())
	while True:
		bmsg = ssock.recv(1024)
		if len(bmsg) <= 0:
			print('read 0; hangup')
			exit(3)
		msg = str(bmsg, 'utf-8').strip()
		jmsg = json.loads(msg)
		print(jmsg)
		msg_type = parse_server_message(jmsg)
		print('parsed msg_type:', msg_type)
		if msg_type == 'query':
			action = get_action(jmsg)
			print('parsed action:', action)
			if action == 'give_card':
				bot_give_card(jmsg)
			elif action == 'select_row':
				bot_select_row(jmsg)
			else:
				print('unknown message action:', action)
		else:
			print('unknown message type:', msg_type)

def bot_give_card(msg):
	print('about to give card')
	hand = msg.get('hand')
	print(hand, '->', hand[0])
	msg = give_card(hand[0])
	send_msg(ssock,msg)
	return hand[0]

def bot_select_row(msg):
	print('about to select row')
	msg = choose_row(0)
	send_msg(ssock,msg)
	return 0




if __name__ == '__main__':
	try:
		while True:
			listen(len(sys.argv)>1)
	except KeyboardInterrupt:
		print('interrupt - exiting')
		#TODO: close
		exit(9)
